package com.hanbo.flymouse.ui.view

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.util.Log
import android.view.ViewConfiguration
import android.view.MotionEvent
import android.view.View
import com.hanbo.flymouse.hid.HidPeripheralService
import com.hanbo.flymouse.hid.HidPeripheralService.Companion.ACTION_MOVE
import com.hanbo.flymouse.hid.HidPeripheralService.Companion.ACTION_CLICK_LEFT
import com.hanbo.flymouse.hid.HidPeripheralService.Companion.ACTION_CLICK_RIGHT
import com.hanbo.flymouse.hid.HidPeripheralService.Companion.ACTION_SCROLL
import com.hanbo.flymouse.hid.HidPeripheralService.Companion.KEY_DX
import com.hanbo.flymouse.hid.HidPeripheralService.Companion.KEY_DY
import kotlin.math.abs
import kotlin.math.roundToInt

class TouchpadView(context: Context) : View(context) {
    private var lastX = 0f
    private var lastY = 0f
    private var downX = 0f
    private var downY = 0f
    private var singleDownTime = 0L
    private var singleMoved = false
    private var lastTwoFingerX = 0f
    private var lastTwoFingerY = 0f
    private var isTwoFingerMode = false
    private var twoFingerStartDistance = 0f
    private var twoFingerDownTime = 0L
    private var twoFingerMoved = false
    private val tapTimeoutMs = ViewConfiguration.getTapTimeout().toLong()
    private val minScrollDistance = 30f // 提高阈值，放慢滚动
    private val minClickDistance = 10f // 最小点击距离
    private val scrollScale = 1.0f // 滚动速度缩放（越小越慢）

    init {
        setBackgroundColor(Color.DKGRAY)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.actionMasked) {
            MotionEvent.ACTION_DOWN -> {
                lastX = event.x
                lastY = event.y
                downX = event.x
                downY = event.y
                singleDownTime = System.currentTimeMillis()
                singleMoved = false
                isTwoFingerMode = false
                return true
            }
            
            MotionEvent.ACTION_POINTER_DOWN -> {
                if (event.pointerCount == 2) {
                    // 双指按下，进入双指模式
                    isTwoFingerMode = true
                    val x1 = event.getX(0)
                    val y1 = event.getY(0)
                    val x2 = event.getX(1)
                    val y2 = event.getY(1)
                    lastTwoFingerX = (x1 + x2) / 2
                    lastTwoFingerY = (y1 + y2) / 2
                    twoFingerStartDistance = kotlin.math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1))
                    twoFingerDownTime = System.currentTimeMillis()
                    twoFingerMoved = false
                    Log.d("TouchpadView", "Two finger down, distance: $twoFingerStartDistance")
                }
                return true
            }
            
            MotionEvent.ACTION_MOVE -> {
                if (isTwoFingerMode && event.pointerCount == 2) {
                    // 双指移动 - 滚动
                    val x1 = event.getX(0)
                    val y1 = event.getY(0)
                    val x2 = event.getX(1)
                    val y2 = event.getY(1)
                    val centerX = (x1 + x2) / 2
                    val centerY = (y1 + y2) / 2
                    
                    val dx = centerX - lastTwoFingerX
                    val dy = centerY - lastTwoFingerY
                    
                    // 只处理垂直滚动，忽略水平滚动
                    if (abs(dy) > minScrollDistance) {
                        val scrollIntent = Intent(context, HidPeripheralService::class.java).apply {
                            action = ACTION_SCROLL
                            putExtra(KEY_DX, 0)
                            putExtra(KEY_DY, (-dy * scrollScale).roundToInt()) // 放慢滚动
                        }
                        context.startService(scrollIntent)
                        lastTwoFingerX = centerX
                        lastTwoFingerY = centerY
                        twoFingerMoved = true
                    }
                } else if (!isTwoFingerMode && event.pointerCount == 1) {
                    // 单指移动 - 鼠标移动
                    val dx = event.x - lastX
                    val dy = event.y - lastY
                    lastX = event.x
                    lastY = event.y
                    if (!singleMoved && kotlin.math.sqrt((event.x - downX) * (event.x - downX) + (event.y - downY) * (event.y - downY)) > minClickDistance) {
                        singleMoved = true
                    }
                    val intent = Intent(context, HidPeripheralService::class.java).apply {
                        action = ACTION_MOVE
                        putExtra(KEY_DX, dx.roundToInt())
                        putExtra(KEY_DY, dy.roundToInt())
                    }
                    context.startService(intent)
                }
                return true
            }
            
            MotionEvent.ACTION_UP -> {
                if (!isTwoFingerMode && event.pointerCount == 1) {
                    // 单指抬起 - 左键点击
                    val pressDuration = System.currentTimeMillis() - singleDownTime
                    val distance = kotlin.math.sqrt((event.x - downX) * (event.x - downX) + (event.y - downY) * (event.y - downY))
                    if (!singleMoved && distance < minClickDistance && pressDuration <= tapTimeoutMs) {
                        // 点击距离很小，认为是点击而不是拖拽
                        val clickIntent = Intent(context, HidPeripheralService::class.java).apply {
                            action = ACTION_CLICK_LEFT
                        }
                        context.startService(clickIntent)
                        Log.d("TouchpadView", "Left click")
                    }
                }
                isTwoFingerMode = false
                return true
            }
            
            MotionEvent.ACTION_POINTER_UP -> {
                if (event.pointerCount == 2) {
                    // 双指抬起 - 右键点击
                    val x1 = event.getX(0)
                    val y1 = event.getY(0)
                    val x2 = event.getX(1)
                    val y2 = event.getY(1)
                    val centerX = (x1 + x2) / 2
                    val centerY = (y1 + y2) / 2
                    val dx = centerX - lastTwoFingerX
                    val dy = centerY - lastTwoFingerY
                    val distance = kotlin.math.sqrt(dx * dx + dy * dy)
                    val pressDuration = System.currentTimeMillis() - twoFingerDownTime
                    // 仅当没有明显滚动/移动且按下时间短，才判定为右键点击
                    if (!twoFingerMoved && distance < minClickDistance && pressDuration <= tapTimeoutMs) {
                        val rightClickIntent = Intent(context, HidPeripheralService::class.java).apply {
                            action = ACTION_CLICK_RIGHT
                        }
                        context.startService(rightClickIntent)
                        Log.d("TouchpadView", "Right click")
                    }
                }
                isTwoFingerMode = false
                return true
            }
        }
        return super.onTouchEvent(event)
    }
}
